package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@RestController("adminDishController")
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @ApiOperation("新增菜品")
    @CacheEvict(cacheNames = "dishCache",allEntries = true)

    public Result add(@RequestBody DishDTO dishDTO) {


       dishService.add(dishDTO);

        return Result.success();
    }
    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        PageResult pageResult = dishService.page(dishPageQueryDTO);
        return Result.success(pageResult);

    }
    @CacheEvict(cacheNames = "dishCache",allEntries = true)

    @DeleteMapping
    public Result deleteAll(Long[] ids){

            dishService.deleteAll(Arrays.asList(ids));

            return Result.success();

    }
    @CacheEvict(cacheNames = "dishCache",allEntries = true)
    @PutMapping
    public Result upDate(@RequestBody DishDTO dishDTO){
          dishService.upDate(dishDTO);

          return Result.success();
    }
    @GetMapping("/{id}")
    public Result<DishVO> findById(@PathVariable Long id){
       DishVO dishVO = dishService.findById(id);
       return Result.success(dishVO);

    }
    @Cacheable(cacheNames = "dishCache",key = "#categoryId")
    @GetMapping("/list")
    public Result findCategoryId(Long categoryId){


      List<Dish>   dish= dishService.findCategoryId(categoryId);

       return Result.success(dish);
    }
    @CacheEvict(cacheNames = "dishCache",allEntries = true)
    @PostMapping("/status/{status}")
    public Result status(@PathVariable Integer status,Long id){
       dishService.status(status,id);

       return Result.success();
    }
    private void  cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}